package com.example.roleplay.controller;

import com.example.roleplay.dto.ASRResponse;
import com.example.roleplay.service.asr.ASRClient;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * ASR（语音识别）API控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/asr")
@RequiredArgsConstructor

public class ASRController {

    private final ASRClient asrClient;

    @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)

    public ResponseEntity<ASRResponse> transcribe(
            @RequestParam("audio") MultipartFile audioFile,
            @RequestParam(defaultValue = "zh-CN") String language) {
        
        try {
            long startTime = System.currentTimeMillis();
            
            // 验证文件类型
            String originalFilename = audioFile.getOriginalFilename();
            if (originalFilename == null || originalFilename.isEmpty()) {
                return ResponseEntity.badRequest().build();
            }

            // 执行语音识别
            String transcriptionText = asrClient.transcribe(audioFile, language);
            
            long processingTime = System.currentTimeMillis() - startTime;
            
            ASRResponse response = ASRResponse.builder()
                    .text(transcriptionText)
                    .confidence(0.95) // 模拟置信度，实际应用中应该从ASR服务返回
                    .language(language)
                    .processingTimeMs(processingTime)
                    .build();

            log.info("ASR识别完成 - 文件: {}, 语言: {}, 结果长度: {}, 耗时: {}ms", 
                    originalFilename, language, transcriptionText.length(), processingTime);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("ASR识别失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    @GetMapping("/health")

    public ResponseEntity<String> checkHealth() {
        boolean isHealthy = asrClient.isHealthy();
        return ResponseEntity.ok(isHealthy ? "OK" : "UNAVAILABLE");
    }

    @GetMapping("/formats")

    public ResponseEntity<String[]> getSupportedFormats() {
        return ResponseEntity.ok(asrClient.getSupportedFormats());
    }

    @GetMapping("/languages")

    public ResponseEntity<String[]> getSupportedLanguages() {
        return ResponseEntity.ok(asrClient.getSupportedLanguages());
    }
}